<?php
	require_once($_SERVER['DOCUMENT_ROOT']."/classes/HumeurDatabase.class.php");
	require_once($_SERVER['DOCUMENT_ROOT']."/classes/GameAnswer.class.php");
	require_once($_SERVER['DOCUMENT_ROOT']."/classes/GaleryItem.interface.php");
	
	class GameSession implements GaleryItem{
		var $id;
		var $memberId;
		var $moodId;
		var $date;
		var $isFinished;
		var $answers;
		
		public function GameSession($data=0){
			if(is_array($data)) $this->create($data);
			elseif(is_numeric($data)) $this->load($data);
		}
		
		public function load($id){
			$db = new HumeurDatabase();
			$data = mysql_fetch_assoc($db->query("SELECT * FROM gameSessions WHERE gameSessionId = '".$id."' LIMIT 1;"));
			$this->create($data);
			$this->loadAnswers();
		}
		
		public function loadAnswers(){
			$db = new HumeurDatabase();
			$this->answers = array();
			$data = $db->query("SELECT answerId FROM gameAnswers WHERE gameSessionId = '".$this->id."';");
			while($answer = mysql_fetch_assoc($data)){
				$this->answers[$answer['answerId']] = new GameAnswer($answer['answerId']);
			}
		}
		
		public function create($array){
			$this->id = (isset($array['gameSessionId']))? $array['gameSessionId']:NULL;
			$this->memberId = (isset($array['memberId']))? $array['memberId']:NULL;
			$this->moodId = (isset($array['moodId']))? $array['moodId']:NULL;
			$this->date = (isset($array['date']))? $array['date']:@date("d-m-Y à H:i:s");
			$this->isFinished = (isset($array['isFinished']))? $array['isFinished']:NULL;
		}
		
		public function save(){
			if($this->id == NULL){
				if(!$this->insert()) return false;
			}else{
				if(!$this->update()) return false;
			}
			
			foreach($this->answers as $answer){
				$answer->gameSessionId = $this->id;
				if(!$answer->save()) return false;
			}
			return true;
		}
		
		public function insert(){
			$db = new HumeurDatabase();
			$result = $db->query("INSERT INTO gameSessions VALUES ('".$this->id."','".$this->memberId."','".$this->moodId."','".$this->date."','".$this->isFinished."');");
			if($result){
				$this->id = mysql_insert_id();
			}
			return $result;
		}
		
		public function delete(){
			$db = new HumeurDatabase();
			$this->loadAnswers();
			foreach($this->answers as $answer){
				$answer->delete();
			}
			return $db->query("DELETE FROM gameSessions WHERE gameSessionId = '".$this->id."';");
		}
		
		public function update(){
			$db = new HumeurDatabase();
			return $db->query("UPDATE gameSessions SET memberId = '".$this->memberId."', moodId = '".$this->moodId."' WHERE gameSessionId = '".$this->id."';");
		}
		
		public function finish($savedResult){
			$this->isFinished = 1;
			if($savedResult){
				$this->save();
			}
			else
			{
				$this->id = uniqid();
			}
		}
		
		public function addAnswer($answer){
			$this->answers[] = $answer;
		}
		
		public function summary(){
			return '<div class="leftAlign gameSession grey">Session du '.$this->date.'. Humeur : '.$this->moodId.'. Statut du test : '.(($this->isFinished == 1)? "Terminé":"Eronné").'.<div class="rightFloat"><a onclick="ajaxLoad(\'loadResult\',\'id='.$this->id.'\',jsonManage)"><img src="img/resultView.png" alt="Visualiser les résultats"/></a></div></div>';
		}
		
		static function compareAnswerWithChosenColorName($a, $b)
		{
			if ($a->chosenColorName == $b->chosenColorName) {
				return 0;
			}
			return ($a->chosenColorName < $b->chosenColorName) ? -1 : 1;
		}
		
		public function makeAnswersJSON(){
			$db = new HumeurDatabase();
			$colors = array();
			usort($this->answers,array("GameSession", "compareAnswerWithChosenColorName"));
			foreach($this->answers as $answer){
				$colors[] = mysql_fetch_assoc($db->query("SELECT * FROM colors WHERE colorName = '".$answer->chosenColorName."';"));
			}
			return json_encode($colors);
		}
		
		function getMoodMusic(){
			$db = new HumeurDatabase();
			$mood = mysql_fetch_assoc($db->query("SELECT music FROM moods WHERE moodName = '".$this->moodId."';"));
			return $mood['music'];
		}
		
		function getInfos(){
			$db = new HumeurDatabase();
			$mood = mysql_fetch_assoc($db->query("SELECT * FROM moods WHERE moodName = '".$this->moodId."';"));
			$member = mysql_fetch_assoc($db->query("SELECT * FROM members WHERE memberId = '".$this->memberId."';"));
			return 'Nom du membre : '.$member['nickname'].'<br/>
					Sexe : '.(($member['gender'] == 1)?"masculin":"féminin").'<br/>
					Date de naissance : '.$member['birthDate'].'<br/>
					Humeur : <img src="img/moods/'.$mood['picture'].'" alt="'.$mood['moodName'].'" /><br/>
							Musique : 
							<object type="application/x-shockwave-flash" data="music/dewplayer.swf" width="200" height="20" id="dewplayer" name="dewplayer">
								<param name="movie" value="music/dewplayer.swf" />
								<param name="flashvars" value="mp3=music/moods/'.$mood['music'].'" />
								<param name="wmode" value="transparent" />
                        	</object><br/>
							Supprimer ces résultats : <img src="img/deleteMember.png" alt="Supprimer les résultats" onclick="ajaxLoad(\'deleteResult\',\'id='.$this->id.'\',jsonManage)" />';
		}
		
		public function __toString(){
			$string = '<h3>Partie du '.$this->date.'</h3><div class="resultMoodInfos">'.$this->getInfos().'</div><div class="leftAlign resultInfos">';
			foreach($this->answers as $answer){
				$string .= $answer;
			}
			
			$string .= '</div><div class="pieChart" id="pie"></div><script>document.getElementById("pie").appendChild(createPieChart(\''.$this->makeAnswersJSON().'\',150));</script>';
			return $string;
		}
			
	}
?>